<?php
defined('IN_PHPCMS') or exit('No permission resources.');

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('phpqrcode','',0);
/**
 * 少儿报名来源管理
 */
class source extends admin
{

    private $db;

    public $siteid;

    public function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('reg_child_source_model');
        $this->reg_db = pc_base::load_model('reg_child_model');
        $this->log = pc_base::load_model('reg_child_log_model');//加载报名记录model
        $this->siteid = get_siteid();
        $this->admin_userid = param::get_cookie('userid');//获取当前登录的管理员ID
        $model_setting=pc_base::load_model('site_setting_model');
        $this->source_url= $model_setting->getValue("reg_child_source_url",$this->siteid);//获取报名地址url
        $this->reg_url = $this->source_url ? $this->source_url : "http://m.emagsoftware.cn/xinsilu/weixin/toRegChildModel?regId=";
    }

    /**
     * 分类列表
     */
    public function init()
    {
        $where = array();
        $where['status'] = 1;
        $where['siteid'] = $this->siteid;
        $tree = pc_base::load_sys_class('tree');
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $categorys = array();
        //获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
        if ($_SESSION['roleid'] == 1) {
        	//读取数据
        	$source_info = $this->db->select($where);
        	foreach ($source_info as $k=>$v){
        		$source_info[$k]['num'] = $this->log->count(array('source'=>$v['source_code'],'channel'=>$v['en_name']));//统计报名主题的报名数量
        	}
        } else {
        	$condition = "";
        	$condition .= "status = 1 and siteid = ".$this->siteid." and parentid =0";
        	$info1 = $this->db->select($condition);
        	foreach ($info1 as $k=>$v){
        		$info1[$k]['num'] = $this->log->count(array('source'=>$v['source_code'],'channel'=>$v['en_name']));//统计报名主题的报名数量
        	}
        	$sql = "";
        	$sql .= "select a.*,b.* from nsrweb_reg_child_source_auth as a LEFT JOIN nsrweb_reg_child_model_source as b on a.source_id = b.id where b.status = 1 and a.userid =".$this->admin_userid;
        	//读取数据
        	$info2 = $this->db->my_listinfo($sql);
        	foreach ($info2 as $k=>$v){
        		$info2[$k]['num'] = $this->log->count(array('source'=>$v['source_code'],'channel'=>$v['en_name']));//统计报名主题的报名数量
        	}
        	$source_info = array_merge($info1,$info2);
        }
//         print_r($source_info);
        if(!empty($source_info)) {
        	foreach($source_info as $r) {
        		$r['str_manage'] = '';
        		if ($r['parentid'] == 0 && $_SESSION['roleid'] == 1) {
        			$r['str_manage'] .= '<a href="javascript:;" onclick="edit1('.$r['id'].', \''.new_addslashes(new_html_special_chars($r['cn_name'])).'\')" title="'.L('add_sub_category').'">'.L('add_sub_category').'</a> | ';
        			$r['str_manage'] .= '<a href="javascript:;" onclick="edit('.$r['id'].', \''.new_addslashes(new_html_special_chars($r['cn_name'])).'\')" title="'.L('edit').'">'.L('edit').' | </a> ';
        			$r['str_manage'] .= '<a href="javascript:confirmurl(\'?m=reg_child&c=source&a=del&id='.$r['id'].'\',\''.L('confirm',array('message'=>addslashes($r['cn_name']))).'\')">'.L('delete').' | </a> ';
        		}
        		if ($r['parentid'] != 0) {
        			$r['str_manage'] .= '<a href="javascript:;" onclick="edit('.$r['id'].', \''.new_addslashes(new_html_special_chars($r['cn_name'])).'\')" title="'.L('edit').'">'.L('edit').' | </a> ';
        			$r['str_manage'] .= '<a href="javascript:confirmurl(\'?m=reg_child&c=source&a=del&id='.$r['id'].'\',\''.L('confirm',array('message'=>addslashes($r['cn_name']))).'\')">'.L('delete').' | </a> ';
        		}
        		$r['str_manage'] .= ' <a href="?m=reg_child&c=manage&a=reg_statistics&source_id='.$r['id'].'&child_source=1&source='.$r['source_code'].'&channel='.$r['en_name'].'">'.L('reg_statistics').'</a> ';
        		if(!empty($r['source_code'])){$r['source_code'] = $r['source_code'];}else{$r['source_code']="<span style='color:red;'>（未设置）</span>";}
        		$r['author'] = $adminInfo[$r['updated_by']];
        		$categorys[$r['id']] = $r;
        	}
        }
        
        $str  = "<tr>
                    <td align='center'>\$id</td>
                    <td align='left'>\$spacer\$cn_name</td>
                    <td align='center'>\$en_name</td>
                    <td align='center'>\$source_code</td>
                    <td align='center'>\$num</td>
                    <td align='center' title='点击可新窗口查看该来源的报名页面！'><a href='\$reg_url' target='_blank'>\$reg_url</a></td>
                    <td align='center' title='点击可新窗口查看该来源的报名二维码图片！'><a href='\$qrcode_img' target='_blank'><img src='\$qrcode_img' height='80'></a></td>
                    <td align='center'>\$update_time</td>
                    <td align='center'>\$author</td>
                    <td align='center'>\$str_manage</td>
                </tr>";
//         print_r($categorys);
        $tree->init($categorys);
        $categorys = $tree->get_tree(0, $str);
//         print_r($categorys);
        $big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=reg_child&c=source&a=add\', title:\''.L('add_source').'\', width:\'700\', height:\'350\'}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_source'));
        include $this->admin_tpl('source_list');
    }

    /**
     * 添加分类
     */
    public function add()
    {
        if (isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $source = $this->check($_POST['source']);
            $source['reg_url'] = $this->reg_url.$source['reg_theme_id'].'&source='.$source['source_code'].'&channel='.$source['en_name'];
            $source['qrcode_img'] = $this->qrcode_image($source['reg_url'],$source['en_name'],$source['logo']);
            $titlepd = $this->public_check_type($source['en_name']);
            $code_exits = $this->public_check_code($source['source_code'],$source['parentid']);
            if (!$titlepd) {
                showmessage('英文标识已经存在', HTTP_REFERER);
            }
            if (!$code_exits) {
                showmessage('来源编码已经存在', HTTP_REFERER);
            }
            $id = $this->db->insert($source, true);

            if ($id) {
            	//记录行为日志
            	$log_content = '<span style="color:#00CC00;">添加分类</span>[分类id：'.$id.'，分类中文名：'.$source['cn_name'].']';
            	$this->manage_admin_log($log_content);
                showmessage(L('operation_success'), HTTP_REFERER, '', 'add');
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }
        } else {
        	//获取报名ID拼接报名地址
        	$where = array();
        	$where['status'] = 1;
        	$where['siteid'] = $this->siteid;
        	$source = $this->reg_db->select($where,'id,title');
        	$reg_info = array();
        	foreach ($source as $v){
        		$reg_info[$v['id']] = $v['title'];
        	}
        	$parent_id = $_GET['parentid'] ? intval($_GET['parentid']) : 0;
        	if ($parent_id!=0) {
        		$data = $this->db->get_one(array('id'=>$parent_id),'source_code');
        	}
            $show_validator = $show_scroll = $show_header = true;
            $select_categorys = $this->db->getSource($parent_id);
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('source_add');
        }
    }

    /**
     * 分类修改
     */
    public function edit()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if (isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $source = $this->check($_POST['source'], 'edit');
            $source['reg_url'] = $this->reg_url.$source['reg_theme_id'].'&source='.$source['source_code'].'&channel='.$source['en_name'];
            $source['qrcode_img'] = $this->qrcode_image($source['reg_url'],$source['en_name'],$source['logo']);
            $titlepd = $this->public_check_type($source['en_name']);
            $code_exits = $this->public_check_code($source['source_code']);
            if (!$titlepd) {
                showmessage('英文标识已经存在', HTTP_REFERER);
            }
            if (!$code_exits) {
            	showmessage('来源编码已经存在', HTTP_REFERER);
            }
            //父级ID为0时，更新所有子类的source_code
            if($source['parentid'] == 0){
            	$data = $this->db->update(array('source_code'=>$source['source_code']),array('parentid'=>$id,'siteid'=>$this->siteid,'status'=>1));
            }
            $ids = $this->db->update($source, array('id' => $id,'siteid' => $this->siteid));

            if ($ids) {
            	//记录行为日志
            	$log_content = '<span style="color:blue;">修改分类</span>[分类id：'.$id.'，分类中文名：'.$source['cn_name'].']';
            	$this->manage_admin_log($log_content);
                showmessage(L('edit_source_success'), HTTP_REFERER, '', 'edit');
            } else {
                showmessage(L('edit_source_error'), HTTP_REFERER);
            }
        } else {
        	//获取报名ID拼接报名地址
        	$where = array();
        	$where['status'] = 1;
        	$where['siteid'] = $this->siteid;
        	$source = $this->reg_db->select($where,'id,title');
        	$reg_info = array();
        	foreach ($source as $v){
        		$reg_info[$v['id']] = $v['title'];
        	}
            $show_validator = $show_scroll = $show_header = true;
            $info = $this->db->get_one(array('id'=>$id, 'siteid'=>$this->siteid));
            $reg_url = parse_url($info['reg_url']);
            $reg_url_info = $this->convertUrlQuery($reg_url['query']);
            $reg_id = $reg_url_info['regId'];
            $parent_id = $info['parentid'];
            if ($parent_id!=0) {
            	$data = $this->db->get_one(array('id'=>$parent_id),'source_code');
            }
            $select_categorys = $this->db->getSource($parent_id);
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('source_edit');
        }
    }

    /**
     * 分类删除
     */
    public function del()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_parameters'), HTTP_REFERER);
        } else {
            $id = intval($_GET['id']);
            $list = $this->db->select(array('parentid'=>$id,'status'=>1,'siteid'=>$this->siteid));
            if ($list) {
                showmessage(L('cateid_zi_fenlei'), HTTP_REFERER);
            }
            if ($id < 1)
                return false;
            $result = $this->db->update(array('status'=>2), array('id' => $id,'siteid' => $this->siteid));

            if ($result) {
            	//记录行为日志
            	$log_content = '<span style="color:red;">删除分类</span>[分类id：'.$id.']';
            	$this->manage_admin_log($log_content);
                showmessage(L('operation_success'), HTTP_REFERER);
            } else {
                showmessage(L("operation_failure"), HTTP_REFERER);
            }
        }
    }

    /**
     * 检验英文标识是否存在，避免英文标识重复
     */
    public function public_check_type ($en_name)
    {
        if(!$en_name) showmessage('英文标识不能为空', HTTP_REFERER);;
        $en_name = addslashes($en_name);
        if($_GET['id']) {
	        $id = intval($_GET['id']);
	        $r = $this->db->get_one(array('id'=>$id, 'siteid' => $this->siteid,'status'=>1));
	        if($r['en_name'] == $en_name) {
	            return true;
	        }
        }
        $r = $this->db->get_one(array('siteid' => $this->siteid, 'en_name' => $en_name,'status'=>1), 'id');
        if($r['id']) {
            return false;
        } else {
            return true;
        }
    }
    
    /**
     * 检验来源编码是否存在，避免来源编码重复
     */
    public function public_check_code ($source_code,$parentid)
    {
    	if(!$source_code) showmessage('来源编码不能为空', HTTP_REFERER);;
    	$source_code = $source_code;
        if($_GET['id']) {
	        $id = intval($_GET['id']);
	        $r = $this->db->get_one(array('id'=>$id, 'siteid' => $this->siteid,'status'=>1));
	        if($r['source_code'] == $source_code) {
	            return true;
	        }
        }
        $r = $this->db->get_one(array('parentid'=>0,'siteid' => $this->siteid, 'source_code' => $source_code,'status'=>1), 'id');
        if (!empty($parentid)) {
        	if($r['id'] && $r['id'] != $parentid) {
        		return false;
        	} else {
        		return true;
        	}
        }
        if($r['id']) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 表单验证
     * 
     * @param array $data
     *            表单传递的值
     * @param string $a
     *            add/edit添加操作时，自动加上默认值
     */
    private function check($data, $a = 'add')
    {
        if ($a == 'add') {
            $data['siteid'] = $this->siteid;
            $data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s');
            $data['created_by'] = $data['updated_by'] = $_SESSION['userid'];
        } else {
            $data['update_time'] = date('Y-m-d H:i:s');
            $data['updated_by'] = $_SESSION['userid'];
        }
        return $data;
    }
    
    /**
     * 添加/修改分类时，如果是子级分类，返回父级分类的source_code
     */
    public function source_code(){
    	$parent_id = $_POST['parentid'];
    	$infos = $this->db->get_one(array('id'=>$parent_id),'source_code');
    	echo json_encode($infos);
    }
    
    /**
     * 根据报名地址生成二维码
     * url:报名地址
     * en_name:英文标识
     */
    private function qrcode_image($url,$en_name,$upload_logo) {
    	$url = $url ? $url : $this->source_url;
    	$value = $url; //二维码内容
    	$errorCorrectionLevel = 'L';//容错级别
    	$matrixPointSize = 6;//生成图片大小
    	$saveandprint = true;
    	$pathname = pc_base::load_config('system','upload_path')."qrcode";
    	if(!is_dir($pathname)) { //若目录不存在则创建之
    		mkdir($pathname);
    	}
    	$filename = $pathname . "/".$en_name . time() . ".png";
    	//生成二维码图片
    	QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2,$saveandprint);
    	//$logo = IMG_PATH.'nsr/qrcode_logo.png';//准备好的logo图片
    	$logo = SITE_PROTOCOL.SITE_URL.$upload_logo;//准备好的logo图片
    	$QR = $filename;//已经生成的原始二维码图
    	
    	if ($logo !== FALSE) {
    		$QR = imagecreatefromstring(file_get_contents($QR));
    		$logo = imagecreatefromstring(file_get_contents($logo));
    		$QR_width = imagesx($QR);//二维码图片宽度
    		$QR_height = imagesy($QR);//二维码图片高度
    		$logo_width = imagesx($logo);//logo图片宽度
    		$logo_height = imagesy($logo);//logo图片高度
    		$logo_qr_width = $QR_width / 5;
    		$scale = $logo_width/$logo_qr_width;
    		$logo_qr_height = $logo_height/$scale;
    		$from_width = ($QR_width - $logo_qr_width) / 2;
    		//重新组合图片并调整大小
    		imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
    				$logo_qr_height, $logo_width, $logo_height);
    	}
    	//输出图片
    	imagepng($QR, $filename);
//     	echo '<img src="'.$en_name.'.png">';
    	$qrcode_name = str_replace('/data', '',$filename);

		return $qrcode_name;
    }
    
    /**
     * 将字符串参数变为数组
     * @param $query
     * @return array array (size=10)
     'm' => string 'content' (length=7)
     'c' => string 'index' (length=5)
     'a' => string 'lists' (length=5)
     'catid' => string '6' (length=1)
     'area' => string '0' (length=1)
     'author' => string '0' (length=1)
     'h' => string '0' (length=1)
     'region' => string '0' (length=1)
     's' => string '1' (length=1)
     'page' => string '1' (length=1)
     */
   private function convertUrlQuery($query)
    {
    	$queryParts = explode('&', $query);
    	$params = array();
    	foreach ($queryParts as $param) {
    		$item = explode('=', $param);
    		$params[$item[0]] = $item[1];
    	}
    	return $params;
    }
}